package com.platform.config;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.springframework.cache.jcache.config.JCacheConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;

import net.oschina.j2cache.redis.RedisUtils;

@Configuration
public class RedisConfig extends JCacheConfigurerSupport {

	private static String adds;
	private static int port;
	private static String password;
	static {

		Properties properties = new Properties();
		// 使用ClassLoader加载properties配置文件生成对应的输入流
		InputStream in = RedisUtils.class.getClassLoader().getResourceAsStream("/j2cache.properties");
		// 使用properties对象加载输入流
		try {
			properties.load(in);
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 获取key对应的value值
		adds = properties.getProperty("redis.adds");
		port = Integer.parseInt(properties.getProperty("redis.port"));
		password = properties.getProperty("redis.password");

	}

	@Bean
	public RedisConnectionFactory redisConnectionFactory() {
		JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
		jedisConnectionFactory.setHostName(adds);
		jedisConnectionFactory.setPort(port);
		jedisConnectionFactory.setPassword(password);
		return jedisConnectionFactory;
	}

	@Bean
	public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
		StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
		stringRedisTemplate.setConnectionFactory(redisConnectionFactory);
		return stringRedisTemplate;
	}
}
